/*
 * Copyright (c) 2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-07-06     Supperthomas first version
 * 2023-12-03     Meco Man     support nano version
 * 2024-04-13     yuanzihao    adaptation for SkyStar STM32F407 version
 */

#include <board.h>
#include <rtthread.h>
#include <drv_gpio.h>
#ifndef RT_USING_NANO
#include <rtdevice.h>
#endif /* RT_USING_NANO */

#define LED GET_PIN(B, 2)
#define KEY GET_PIN(A, 0)
#define LOC(i) 0x01 << i

rt_thread_t key, led;
rt_event_t e1;
rt_device_t uart_dev;
struct serial_configure uart_config;
rt_int8_t recv_buf[50] = {0};
rt_int8_t id;

void init()
{
    rt_pin_mode(KEY, PIN_MODE_INPUT);
    rt_pin_mode(LED, PIN_MODE_OUTPUT);
}
void key_entry(void *p)
{
    while (1)
    {
        if (rt_pin_read(KEY) == 1)
        {
            rt_event_send(e1, LOC(1));
            rt_kprintf("key\n");
        }
        rt_thread_mdelay(300);
    }
}
void led_entry(void *p)
{
    rt_uint32_t result = 0x00;
    while (1)
    {
        rt_event_recv(e1, LOC(1), RT_EVENT_FLAG_AND | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, 0);
        if (result)
        {
            result = 0;
        }
        else
        {
            result = 1;
        }
        rt_kprintf("status:%d\n", result);
        rt_pin_write(LED, result);
    }
}

rt_err_t uart_func()
{
    rt_int8_t buf;
    rt_device_read(uart_dev, 0, &buf, 1);
    recv_buf[id++] = buf;
    if (buf == '\n')
    {
        id--;
        recv_buf[id++] = '_';
        recv_buf[id++] = '\n';
        recv_buf[id++] = '\0';
        rt_device_write(uart_dev, 0, recv_buf, id);
        id = 0;
    }
    return RT_EOK;
}
int key_led_uart2_main(void)
{
    init();

    rt_int8_t result = 0;
    uart_dev = rt_device_find("uart2");
    if (uart_dev == RT_NULL)
        rt_kprintf("find uart failed\n");
    result = rt_device_open(uart_dev, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
    if (result < 0)
        rt_kprintf("serial open failed\n");
    else
    {
        uart_config.baud_rate = 115200;
        rt_device_control(uart_dev, RT_DEVICE_CTRL_CONFIG, (void *)&uart_config);
        rt_device_set_rx_indicate(uart_dev, uart_func);
    }
    e1 = rt_event_create("led", RT_IPC_FLAG_FIFO);
    key = rt_thread_create("key", key_entry, RT_NULL, 512, 15, 5);
    rt_thread_startup(key);
    led = rt_thread_create("led", led_entry, RT_NULL, 512, 18, 5);
    rt_thread_startup(led);
}
